package hanhns.test.addNote;

import hanhns.test.R;
import hanhns.test.database.DBAdapter;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import constant.*;

public class NewNote extends Activity{
	private DBAdapter dbAdapter;
	private EditText title;
	private EditText content;
	private String type;
	private int id_note;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_note);
		Intent intent = getIntent();
		title = (EditText) findViewById(R.id.title);
		content = (EditText) findViewById(R.id.content);
		type = intent.getStringExtra(Constant.type);
		Toast.makeText(this, type, Toast.LENGTH_SHORT).show();
		if(type.equals(Constant.update_note)){
			
			title.setText(intent.getStringExtra(Constant.title));
			
			content.setText(intent.getStringExtra(Constant.content));
			
			id_note = intent.getIntExtra(Constant._id, 0);
		}
		
		dbAdapter = new DBAdapter(this);
		
		
		Button save = (Button) findViewById(R.id.save_button);
		save.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String newTitle = title.getText().toString();
				Log.e("new note", "new title: " + newTitle);
				String newContent = content.getText().toString();
				if(newTitle.equalsIgnoreCase("") || newContent.equalsIgnoreCase("")){
					showmessage("you have input note tile and content!!");
				}else{
					if(type.equals(Constant.update_note)){
						dbAdapter.open();
						dbAdapter.updateTitle(id_note, newTitle, newContent);
						Log.e("update", "id: " + id_note);
						dbAdapter.close();
					}else {
						dbAdapter.open();
						dbAdapter.insertNote(newTitle, newContent);
						dbAdapter.close();
						
					}
					finish();
				}
				
				
			}
		});
	}
	
	private void showmessage(String message){
		Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(title.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(content.getWindowToken(), 0);
	}
	
}
